package admin

import (
	"log"
	"net/http"
	"time"

	"poetry/database"
	"poetry/middleware/jwt"
	"poetry/model"

	jwtgo "github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

// Register 验证注册
type Register struct {
	Name     string `json:"name"`
	Password string `json:"password"`
	Email    string `json:"email"`
}

// HandlerRegister 用户注册
func HandlerRegister(c *gin.Context) {

	var register Register
	if err := c.ShouldBindJSON(&register); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var user model.User
	if err := database.DB.Where("name = ?", register.Name).Find(&user).Error; err != nil {
		user.Name = register.Name
		user.Password = register.Password
		user.Email = register.Email
		database.DB.Save(&user)

		c.JSON(http.StatusOK, gin.H{
			"code":    0,
			"data":    true,
			"msg": "注册成功",
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"data":    true,
			"msg": "用户已存在",
		})
	}
}

// Login 验证登陆
type Login struct {
	Name     string `json:"name" binding:"required"`
	Password string `json:"password" binding:"required"`
}

// HandlerLogin 用户登陆
func HandlerLogin(c *gin.Context) {
	var login Login
	if err := c.ShouldBindJSON(&login); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"msg": "请输入正确的账号密码",
		})
		return
	} else {
		var user model.User
		if err := database.DB.Where("name = ?", login.Name).Find(&user).Error; err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    -1,
				"msg": "请输入正确的账号密码",
			})
			return
		}
		log.Println(login)
		log.Println(user)
		if login.Password != user.Password {
			c.JSON(http.StatusOK, gin.H{
				"code":    -1,
				"msg": "明确告诉你，密码不正确！",
			})
			return
		} else {
			generateToken(c, user)
		}
	}
}

func generateToken(c *gin.Context, user model.User) {
	j := &jwt.JWT{
		SigningKey: []byte("newtrekWang"),
	}
	claims := jwt.CustomClaims{
		user.ID,
		user.Name,
		jwtgo.StandardClaims{
			NotBefore: int64(time.Now().Unix() - 1000), // 签名生效时间
			ExpiresAt: int64(time.Now().Unix() + 3600), // 过期时间 一小时
			Issuer:    "newtrekWang",                   //签名的发行者
		},
	}
	token, err := j.CreateToken(claims)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    -1,
			"msg": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg": "登录成功",
		"data": gin.H{
			"token": token,
			"name": user.Name,
		},
	})
	return
}
